import { Request, Response } from 'express';
import { AppDataSource } from '../../config/database';
import { SystemMessage, MessageStatus, MessageType } from '../../entities/SystemMessage';
import { Repository, Not } from 'typeorm';
import { AuthRequest } from '../../types/auth';

/**
 * 消息控制器 - APP端
 */
export class MessageAppController {
  private messageRepository: Repository<SystemMessage>;

  constructor() {
    this.messageRepository = AppDataSource.getRepository(SystemMessage);
  }

  /**
   * 查询用户消息列表
   * 同时返回未读消息数量，简化APP接口调用
   * @route GET /app/message/list
   */
  async getUserMessages(req: AuthRequest, res: Response) {
    try {
      const currentUser = req.user;

      if (!currentUser || !currentUser.id) {
        return res.status(401).json({
          success: false,
          message: '用户未登录'
        });
      }

      // 获取分页参数
      const page = parseInt(req.query.page as string) || 1;
      const pageSize = parseInt(req.query.pageSize as string) || 10;

      console.log(`查询用户 ${currentUser.id} 的消息列表，页码: ${page}, 每页数量: ${pageSize}`);

      // 同时执行多个查询以提高性能
      const [messages, totalCount, unreadCount] = await Promise.all([
        // 1. 查询消息列表
        this.messageRepository.find({
          where: {
            userId: currentUser.id,
            status: Not(MessageStatus.DELETED) // 只排除已删除的消息
          },
          order: {
            createTime: 'DESC', // 按创建时间降序排序，最新的消息排在前面
            id: 'DESC'
          },
          skip: (page - 1) * pageSize,
          take: pageSize
        }),
        
        // 2. 查询总消息数量
        this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: Not(MessageStatus.DELETED)
          }
        }),
        
        // 3. 查询未读消息数量
        this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD
          }
        })
      ]);

      return res.json({
        success: true,
        data: {
          total: totalCount,
          unreadCount: unreadCount,
          page,
          pageSize,
          messages: messages.map(msg => ({
            id: msg.id,
            title: msg.title,
            content: msg.content,
            type: msg.type,
            typeText: msg.typeText,
            status: msg.status,
            statusText: msg.statusText,
            url: msg.url,
            createTime: msg.createTime,
            isRead: msg.status === MessageStatus.READ
          })),
          hasNextPage: page * pageSize < totalCount
        }
      });
    } catch (error: any) {
      console.error('获取用户消息列表失败:', error);
      return res.status(500).json({
        success: false,
        message: '获取用户消息列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取用户未读消息数量（简化版）
   * 仅返回未读消息总数，性能更好
   * @route GET /app/message/unread-count
   */
  async getSimpleUnreadCount(req: AuthRequest, res: Response) {
    try {
      const currentUser = req.user;

      if (!currentUser || !currentUser.id) {
        return res.status(401).json({
          success: false,
          message: '用户未登录'
        });
      }

      // 只统计未读消息总数
      const unreadCount = await this.messageRepository.count({
        where: {
          userId: currentUser.id,
          status: MessageStatus.UNREAD
        }
      });

      return res.json({
        success: true,
        data: {
          unreadCount
        }
      });
    } catch (error: any) {
      console.error('获取未读消息数量失败:', error);
      return res.status(500).json({
        success: false,
        message: '获取未读消息数量失败',
        error: error.message
      });
    }
  }

  /**
   * 标记消息为已读
   * 并返回更新后的未读消息数量
   * @route PUT /app/message/read/:messageId
   */
  async markMessageAsRead(req: AuthRequest, res: Response) {
    try {
      const currentUser = req.user;

      if (!currentUser || !currentUser.id) {
        return res.status(401).json({
          success: false,
          message: '用户未登录'
        });
      }

      const { messageId } = req.params;

      if (!messageId) {
        return res.status(400).json({
          success: false,
          message: '缺少消息ID'
        });
      }

      // 开始事务
      const queryRunner = AppDataSource.createQueryRunner();
      await queryRunner.connect();
      await queryRunner.startTransaction();

      try {
        // 查询消息
        const message = await queryRunner.manager.findOne(SystemMessage, {
          where: {
            id: messageId,
            userId: currentUser.id
          }
        });

        if (!message) {
          await queryRunner.rollbackTransaction();
          return res.status(404).json({
            success: false,
            message: '消息不存在'
          });
        }

        // 如果消息已经是已读状态，直接返回未读消息数量
        if (message.status === MessageStatus.READ) {
          await queryRunner.rollbackTransaction();
          
          // 查询未读消息数量
          const unreadCount = await this.messageRepository.count({
            where: {
              userId: currentUser.id,
              status: MessageStatus.UNREAD
            }
          });
          
          return res.json({
            success: true,
            message: '消息已经是已读状态',
            data: {
              unreadCount
            }
          });
        }

        // 更新消息状态为已读
        message.status = MessageStatus.READ;
        await queryRunner.manager.save(message);

        // 查询未读消息数量
        const unreadCount = await queryRunner.manager.count(SystemMessage, {
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD
          }
        });

        await queryRunner.commitTransaction();

        return res.json({
          success: true,
          message: '已将消息标记为已读',
          data: {
            unreadCount
          }
        });
      } catch (error) {
        await queryRunner.rollbackTransaction();
        throw error;
      } finally {
        await queryRunner.release();
      }
    } catch (error: any) {
      console.error('标记消息为已读失败:', error);
      return res.status(500).json({
        success: false,
        message: '标记消息为已读失败',
        error: error.message
      });
    }
  }

  /**
   * 标记全部消息为已读
   * 一键将所有未读消息标记为已读
   * @route PUT /app/message/read-all
   */
  async markAllMessagesAsRead(req: AuthRequest, res: Response) {
    try {
      const currentUser = req.user;

      if (!currentUser || !currentUser.id) {
        return res.status(401).json({
          success: false,
          message: '用户未登录'
        });
      }

      // 开始一个查询运行器
      const queryRunner = AppDataSource.createQueryRunner();
      await queryRunner.connect();
      await queryRunner.startTransaction();

      try {
        // 更新所有未读消息为已读
        const updateResult = await queryRunner.manager.update(
          SystemMessage,
          {
            userId: currentUser.id,
            status: MessageStatus.UNREAD
          },
          { status: MessageStatus.READ }
        );

        await queryRunner.commitTransaction();

        const affectedCount = updateResult.affected || 0;
        
        // 查询操作后的未读消息数量
        const remainingUnreadCount = await this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD
          }
        });
        
        return res.json({
          success: true,
          message: `已将${affectedCount}条消息标记为已读`,
          data: {
            affectedCount,
            unreadCount: remainingUnreadCount
          }
        });
      } catch (error) {
        await queryRunner.rollbackTransaction();
        throw error;
      } finally {
        await queryRunner.release();
      }
    } catch (error: any) {
      console.error('标记全部消息为已读失败:', error);
      return res.status(500).json({
        success: false,
        message: '标记全部消息为已读失败',
        error: error.message
      });
    }
  }

  /**
   * 删除消息
   * @route DELETE /app/message/:messageId
   */
  async deleteMessage(req: AuthRequest, res: Response) {
    try {
      const currentUser = req.user;

      if (!currentUser || !currentUser.id) {
        return res.status(401).json({
          success: false,
          message: '用户未登录'
        });
      }

      const { messageId } = req.params;

      if (!messageId) {
        return res.status(400).json({
          success: false,
          message: '缺少消息ID'
        });
      }

      // 查询消息
      const message = await this.messageRepository.findOne({
        where: {
          id: messageId,
          userId: currentUser.id
        }
      });

      if (!message) {
        return res.status(404).json({
          success: false,
          message: '消息不存在'
        });
      }

      // 更新消息状态为已删除
      message.status = MessageStatus.DELETED;
      await this.messageRepository.save(message);

      return res.json({
        success: true,
        message: '消息已删除'
      });
    } catch (error: any) {
      console.error('删除消息失败:', error);
      return res.status(500).json({
        success: false,
        message: '删除消息失败',
        error: error.message
      });
    }
  }

  /**
   * 获取用户未读消息详细统计信息
   * 按消息类型分类统计未读消息数量
   * @route GET /app/message/unread-stats
   */
  async getUnreadStats(req: AuthRequest, res: Response) {
    try {
      const currentUser = req.user;

      if (!currentUser || !currentUser.id) {
        return res.status(401).json({
          success: false,
          message: '用户未登录'
        });
      }

      // 按类型统计未读消息数量
      const unreadCounts = await Promise.all([
        // 总未读消息数
        this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD
          }
        }),
        // 系统消息未读数
        this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD,
            type: MessageType.SYSTEM
          }
        }),
        // 录取消息未读数
        this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD,
            type: MessageType.ADMISSION
          }
        }),
        // 缴费消息未读数
        this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD,
            type: MessageType.PAYMENT
          }
        }),
        // 其他消息未读数
        this.messageRepository.count({
          where: {
            userId: currentUser.id,
            status: MessageStatus.UNREAD,
            type: MessageType.OTHER
          }
        })
      ]);

      return res.json({
        success: true,
        data: {
          total: unreadCounts[0],
          system: unreadCounts[1],
          admission: unreadCounts[2],
          payment: unreadCounts[3],
          other: unreadCounts[4]
        }
      });
    } catch (error: any) {
      console.error('获取未读消息统计失败:', error);
      return res.status(500).json({
        success: false,
        message: '获取未读消息统计失败',
        error: error.message
      });
    }
  }
}

// 导出控制器实例
export const messageAppController = new MessageAppController(); 